<template>
  <div class="look-post">
    <div class="left">
      <opera-btn
        @openDrawer="openDrawer"
        :postId="parseInt(postId)"
      ></opera-btn>
    </div>
    <div class="post-content">
      <div class="article">
        <!-- 骨架屏 -->
        <el-skeleton
          :rows="20"
          animated
          v-if="Object.keys(postData).length === 0"
        />
        <!-- 标题 -->
        <div class="top" v-else>
          <span class="title">{{ postData.title }}</span>
          <div class="post-info">
            <div class="left">
              <div class="username">{{ postData.username }}</div>
              <div class="time">{{ formatDate(postData.createTime) }}</div>
              <div class="pageView">
                <svg-icon icon-file-name="eye"></svg-icon>
                {{ computedPageViewAndLikes(postData.pageView) }}
              </div>
            </div>
            <div class="right">
              <el-tag
                size="mini"
                type="info"
                effect="plain"
                v-for="(name, index) in postData.tagNames"
                :key="index"
                >{{ name }}</el-tag
              >
            </div>
          </div>
        </div>
        <!-- 正文 -->
        <div
          class="content"
          v-html="renderMdText(markdownText)"
          ref="markdownContent"
        ></div>
      </div>
      <!-- 评论 -->
      <comment
        v-if="!isImmerse"
        :postUserId="postData.userId"
        :postId="parseInt(postId)"
      ></comment>
      <el-drawer
        ref="commentDrawer"
        :visible.sync="commentDrawer"
        :with-header="false"
      >
        <comment :postUserId="postData.userId" :postId="postId"></comment>
      </el-drawer>
    </div>
    <div class="right">
      <div style="background-color: #fff" v-if="!isImmerse">
        <el-skeleton
          :rows="6"
          animated
          v-if="Object.keys(postData).length === 0"
        />
        <!-- 作者详细信息 -->
        <author v-else :postId="parseInt(postId)"></author>
      </div>
      <div class="directory">
        <div class="top">目录</div>
        <el-skeleton
          :rows="6"
          animated
          v-if="Object.keys(postData).length === 0"
        />
        <div
          v-else
          class="bottom"
          v-html="renderMdDirectory(markdownText)"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import MarkdownIt from "markdown-it";
import hljs from "highlight.js";
import "highlight.js/styles/atom-one-light.css"; // 导入样式
import tocDoneRight from "markdown-it-toc-done-right"; // 目录
import { getPostInfoById } from "../../api/post";
import Author from "./components/AuthorView.vue";
import OperaBtn from "./components/operaBtn.vue";
import Comment from "./components/CommentView.vue";
export default {
  components: {
    Author,
    OperaBtn,
    Comment,
  },
  data() {
    return {
      // 评论抽屉
      commentDrawer: false,
      // 是否显示骨架屏
      isShow: true,
      // 帖子内容
      markdownText: "",
      postId: "",
      postTitle: "",
      data: {},
      postData: {},
      authorData: {},
      md: new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        breaks: true,
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return hljs.highlight(lang, str).value;
            } catch (__) {
              // asd
            }
          }
          return ""; // 使用默认的转义方式
        },
      }).use(tocDoneRight, {
        containerClass: "table-of-contents",
        listType: "ul",
      }),
    };
  },
  methods: {
    // 打开左侧的评论抽屉
    openDrawer() {
      this.commentDrawer = true;
    },
    // 处理日期
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 计算阅读量
    computedPageViewAndLikes(count) {
      if (count < 1000) {
        return count;
      } else {
        return (count / 1000).toFixed(1) + "k";
      }
    },
    getPostData() {
      getPostInfoById(this.postId).then((res) => {
        if (res.data.code === 1) {
          this.postData = res.data.data;
          this.markdownText = res.data.data.content;
        } else {
          this.$message.error("获取帖子信息失败");
        }
      });
    },
    // 解析内容
    renderMdText(text) {
      return this.md.render(text);
    },
    // 解析目录
    renderMdDirectory(text) {
      const renderedHtml = this.md.render(`[[toc]]\n${text}`);
      this.$nextTick(() => {
        const tocLinks = this.$el.querySelectorAll(".table-of-contents a");
        tocLinks.forEach((link) => {
          link.addEventListener("click", (event) => {
            event.preventDefault();
            // 获取点击的目录标题内容
            const targetId = link.textContent.trim();
            // 获取页面所有的标题
            const headings = document.querySelectorAll(
              "h1, h2, h3, h4, h5, h6"
            );
            // 查找与目标标题内容相同的标题元素
            const conclusionHeading = Array.from(headings).find((heading) => {
              return heading.textContent.trim() === targetId;
            });
            // 如果找到了标题元素，则滚动到该元素的位置
            if (conclusionHeading) {
              conclusionHeading.scrollIntoView({
                behavior: "smooth",
                block: "start",
              });
            }
          });
        });
      });
      const tempDiv = document.createElement("div");
      tempDiv.innerHTML = renderedHtml;
      const tocElement = tempDiv.querySelector(".table-of-contents");
      return tocElement ? tocElement.outerHTML : "";
    },
    // 更新标题
    updateTitle() {
      document.title = this.postTitle;
    },
  },
  created() {
    this.postId = this.$route.params.postId;
    this.postTitle = this.$route.params.postTitle;
  },
  computed: {
    ...mapState({
      isImmerse: (state) => state.Immerse.isImmerse,
    }),
  },
  mounted() {
    this.getPostData();
    this.updateTitle();
  },
  watch: {
    postTitle() {
      this.updateTitle();
    },
  },
};
</script>

<style lang="less" scoped>
.look-post {
  margin-top: 20px;
  margin-left: 10%;
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  .left,
  .post-content {
    border-radius: 5px;
  }
  .left {
    padding: 10x;
    margin-right: 10px;
  }
  .post-content {
    width: 60%;
    .article {
      padding: 20px;
      border-radius: 5px;
      background-color: #fff;
      .top {
        display: flex;
        flex-direction: column;
        margin-bottom: 30px;
        gap: 10px;
        .title {
          font-size: 30px;
          font-weight: 800;
          margin-bottom: 10px;
        }
        .post-info {
          color: #8a91ab;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .left {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 15px;
            .username {
              color: #515767;
            }
            .pageView {
              display: flex;
              align-items: center;
            }
          }
          .right {
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center;
          }
        }
      }
      .content {
        line-height: 30px;
        /deep/ p {
          line-height: 30px !important;
        }
      }
    }
  }
  .right {
    width: 18%;
    display: flex;
    flex-direction: column;
    gap: 20px;
    /deep/ .el-skeleton {
      width: 85%;
      margin: 20px;
    }
    .directory {
      // 绝对定位，不随着滚动条滚动
      position: sticky;
      top: 20px;
      padding: 0 10px 0 10px;
      background-color: #fff;
      border-radius: 5px;
      .top {
        padding: 15px;
        margin: 0 10px;
        font-size: 16px;
        color: #252933;
        border-bottom: 1px solid #e4e6eb;
      }
      .bottom {
        height: 200px;
        overflow-y: auto;
        padding-top: 5px;
        /* 自定义滚动条样式 */
        &::-webkit-scrollbar {
          width: 5px; /* 滚动条宽度 */
        }
        &::-webkit-scrollbar-track {
          background: #f2f3f5; /* 滚动条轨道背景色 */
          border-radius: 4px; /* 滚动条轨道圆角 */
        }
        &::-webkit-scrollbar-thumb {
          background: #ccc; /* 滚动条颜色 */
          border-radius: 4px; /* 滚动条圆角 */
        }
        &::-webkit-scrollbar-thumb:hover {
          background: #555; /* 滚动条悬停颜色 */
        }
        /deep/ .table-of-contents {
          ul {
            padding-left: 10px;
            li {
              padding-left: 10px;
              list-style-type: none;
              a {
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 23px;
                text-decoration: none;
                color: #252933;
                &:hover {
                  color: #1e80ff;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
/deep/ img {
  width: 100%;
}

/deep/ pre {
  margin-top: 10px;
  background-color: #f8f8f8;
  border-radius: 2px;
  overflow-x: auto;
  padding: 10px;
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 20px;
  code {
    font-size: 16px;
  }
}
</style>

